package com.chizha.common;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.validate.Validator;


/**
 * 本 demo 仅表达最为粗浅的 jfinal 用法，更为有价值的实用的企业级用法
 * 详见 JFinal 俱乐部: http://jfinal.com/club
 * 
 * BlogValidator.
 */
public class ParamValidator extends Validator {
	
	protected void validate(Controller controller) {
		String actionKey = getActionKey();
		if(actionKey.equals("/login/loginCheck")){
			if(validateCode("code","codeMsg","账号错误")){
				validatePassword("password", "passwordMsg", "密码错误");
			}			
		}
	}

	@Override
	protected void handleError(Controller c) {
		String actionKey = getActionKey();
		if(actionKey.equals("/login/loginCheck")){
			c.keepPara();
			c.render("login.html");
		}	
	}
	
	/**
	 * 验证账号正确性
	 * 
	 * @param field
	 * @param errorKey
	 * @param errorMsg
	 */
	protected Boolean validateCode(String field, String errorKey, String errorMsg){
		Boolean flag = true;
		try {
            String value = controller.getPara(field);
            int count = Db.findFirst("select count(*) count from r_user where code = '"+value+"'").getLong("count").intValue();
            if (count < 1) {
                addError(errorKey, errorMsg);
                flag = false;
            }
        } catch (Exception e) {
            addError(errorKey, "账号错误");
            flag = false;
        }
		return flag;
	}
	
	/**
	 * 验证账号密码匹配
	 * 
	 * @param field
	 * @param errorKey
	 * @param errorMsg
	 */
	protected void validatePassword(String field, String errorKey, String errorMsg){
		try {
			String code = controller.getPara("code");
			String password = Db.findFirst("select password from r_user where code = '"+code+"'").getStr("password");			
            String value = MD5Util.getMD5(controller.getPara("password"));
            if (!password.equals(value)) {
                addError(errorKey, errorMsg);
                return;
            }
        } catch (Exception e) {
            addError(errorKey, "密码错误");
        }
	}
	
	/**
	 * 验证消息是否为JSON
	 * 
	 * @param field
	 * @param errorKey
	 * @param errorMsg
	 */
	protected void validateJSON(String field, String errorKey, String errorMsg){
		try {
			String value = controller.getPara(field);
			JSONObject json = JSONObject.parseObject(value);
        } catch (Exception e) {
            addError(errorKey, "消息格式错误");
        }
	}
	
}
